//
//  MapViewController.m
//  GuideMe
//
//  Created by Amila Fonseka on 3/24/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "MapViewController.h"
#import "ArboretumAnnotation.h"
#import "GuideMeAppDelegate.h"

@implementation MapViewController
@synthesize iSelection;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (IBAction)goBack:(id)sender {
	[self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)showTransportLocations:(id)sender {
	iSelection=1;
	[self setButtonImagesForSelection];
}

- (IBAction)showRestaurantLocations:(id)sender {
	iSelection=2;
	[self setButtonImagesForSelection];
}

//- (IBAction)showLocalLocations:(id)sender {
//	iSelection=3;
//	[self setButtonImagesForSelection];
//}


- (void)setButtonImagesForSelection {
	if (iSelection==1) {
		[btnTransport setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"TransportMapSelect" ofType:@"png"]] forState:UIControlStateNormal];
		[btnrestaurant setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"RestaurantMap" ofType:@"png"]] forState:UIControlStateNormal];
		//[btnLocal setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"LocalMap" ofType:@"png"]] forState:UIControlStateNormal];
		
        [self clearLocationsOfMapONLY];
        
        // create the overlay
        [self loadRoute];
        
        // add the overlay to the map
        if (nil != _routeLine) {
            [mapView addOverlay:_routeLine];
        }
        
        // zoom in on the route. 
        [self zoomInOnRoute];
        
        iSelection=1;
		//[self clearLocationsOfMap];
		
	} else if (iSelection==2) {
		iSelection=2;
		[self clearLocationsOfMap];
        
		[btnTransport setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"TransportMap" ofType:@"png"]] forState:UIControlStateNormal];
		[btnrestaurant setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"RestaurantMapSelect" ofType:@"png"]] forState:UIControlStateNormal];
		//[btnLocal setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"LocalMap" ofType:@"png"]] forState:UIControlStateNormal];
		
	}
//    else if (iSelection==3) {
//        //iSelection=3;
//        //[self clearLocationsOfMap];
//		[btnTransport setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"TransportMap" ofType:@"png"]] forState:UIControlStateNormal];
//		[btnrestaurant setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"RestaurantMap" ofType:@"png"]] forState:UIControlStateNormal];
//		[btnLocal setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"LocalMapSelect" ofType:@"png"]] forState:UIControlStateNormal];
//		
//	}
}


// creates the route (MKPolyline) overlay
-(void) loadRoute
{
	NSString* filePath = [[NSBundle mainBundle] pathForResource:@"route" ofType:@"csv"];
	NSString* fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
	NSArray* pointStrings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	
	
	// while we create the route points, we will also be calculating the bounding box of our route
	// so we can easily zoom in on it. 
	MKMapPoint northEastPoint; 
	MKMapPoint southWestPoint; 
	
	// create a c array of points. 
	MKMapPoint* pointArr = malloc(sizeof(CLLocationCoordinate2D) * pointStrings.count);
	
	for(int idx = 0; idx < pointStrings.count; idx++)
	{
		// break the string down even further to latitude and longitude fields. 
		NSString* currentPointString = [pointStrings objectAtIndex:idx];
		NSArray* latLonArr = [currentPointString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
        
		CLLocationDegrees latitude  = [[latLonArr objectAtIndex:0] doubleValue];
		CLLocationDegrees longitude = [[latLonArr objectAtIndex:1] doubleValue];
        
        
		// create our coordinate and add it to the correct spot in the array 
		CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
        
		MKMapPoint point = MKMapPointForCoordinate(coordinate);
        
		
		//
		// adjust the bounding box
		//
		
		// if it is the first point, just use them, since we have nothing to compare to yet. 
		if (idx == 0) {
			northEastPoint = point;
			southWestPoint = point;
		}
		else 
		{
			if (point.x > northEastPoint.x) 
				northEastPoint.x = point.x;
			if(point.y > northEastPoint.y)
				northEastPoint.y = point.y;
			if (point.x < southWestPoint.x) 
				southWestPoint.x = point.x;
			if (point.y < southWestPoint.y) 
				southWestPoint.y = point.y;
		}
        
		pointArr[idx] = point;
        
	}
	
	// create the polyline based on the array of points. 
	_routeLine = [MKPolyline polylineWithPoints:pointArr count:pointStrings.count];
    
	_routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y, northEastPoint.x - southWestPoint.x, northEastPoint.y - southWestPoint.y);
    
	// clear the memory allocated earlier for the points
	free(pointArr);
	
}

-(void) zoomInOnRoute
{
	[mapView setVisibleMapRect:_routeRect];
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}


#pragma mark Map Loading Method

- (void)loadLocationsWithLatLong
{
	ArboretumAnnotation *arboAnnot = [[ArboretumAnnotation alloc] init];
	CLLocationCoordinate2D workingCoord;
	workingCoord.latitude = [[[[arryLocationDetails objectAtIndex:iSelection-1] objectAtIndex:0] objectForKey:@"Lat"] doubleValue];
	workingCoord.longitude = [[[[arryLocationDetails objectAtIndex:iSelection-1] objectAtIndex:0] objectForKey:@"Long"] doubleValue];
	[arboAnnot setCoordinate:workingCoord];
	[arboAnnot setTitle:@"Dinemore"];
	[arboAnnot setSubtitle:@"432, York Mawatha, London Handiya."];
	arboAnnot.image=[UIImage imageNamed:@"Location.png"];
    [mapView addAnnotation:arboAnnot];
	[arboAnnot release];
	
	ArboretumAnnotation *arboAnnot2 = [[ArboretumAnnotation alloc] init];
	CLLocationCoordinate2D workingCoord2;
	workingCoord2.latitude = [[[[arryLocationDetails objectAtIndex:iSelection-1] objectAtIndex:1] objectForKey:@"Lat"] doubleValue];
	workingCoord2.longitude = [[[[arryLocationDetails objectAtIndex:iSelection-1] objectAtIndex:1] objectForKey:@"Long"] doubleValue];
	[arboAnnot2 setCoordinate:workingCoord2];
	[arboAnnot2 setTitle:@"Pizza Hut"];
	[arboAnnot2 setSubtitle:@"Westminster, London."];
	arboAnnot2.image=[UIImage imageNamed:@"Location.png"];
	[mapView addAnnotation:arboAnnot2];
	[arboAnnot2 release];
	
	ArboretumAnnotation *arboAnnot3 = [[ArboretumAnnotation alloc] init];
	CLLocationCoordinate2D workingCoord3;
	workingCoord3.latitude = [[[[arryLocationDetails objectAtIndex:iSelection-1] objectAtIndex:2] objectForKey:@"Lat"] doubleValue];
	workingCoord3.longitude = [[[[arryLocationDetails objectAtIndex:iSelection-1] objectAtIndex:2] objectForKey:@"Long"] doubleValue];
	[arboAnnot3 setCoordinate:workingCoord3];
	[arboAnnot3 setTitle:@"Cafe on the 5th"];
	[arboAnnot3 setSubtitle:@"5th Lane, London."];
    arboAnnot3.image=[UIImage imageNamed:@"Location.png"];
	//arboAnnot2.image=[UIImage imageNamed:@"icon.png"];
	[mapView addAnnotation:arboAnnot3];
	[arboAnnot3 release];
	
	MKCoordinateRegion region;
	MKCoordinateSpan span;
	span.latitudeDelta=0.005;
	span.longitudeDelta=0.005;
	
	region.span=span;
	region.center=workingCoord;
	[mapView setRegion:region animated:TRUE];
	[mapView regionThatFits:region];
}

- (void)clearLocationsOfMap {
	NSMutableArray *toRemove = [NSMutableArray arrayWithCapacity:10];
	for (id annotation in mapView.annotations)
		if (annotation != mapView.userLocation)
			[toRemove addObject:annotation];
	[mapView removeAnnotations:toRemove];
    //londonMapView.showsUserLocation = YES;
	[self loadLocationsWithLatLong];
}

- (void)clearLocationsOfMapONLY {
	NSMutableArray *toRemove = [NSMutableArray arrayWithCapacity:10];
	for (id annotation in mapView.annotations)
		if (annotation != mapView.userLocation)
			[toRemove addObject:annotation];
	[mapView removeAnnotations:toRemove];
    //londonMapView.showsUserLocation = YES;
}

#pragma mark Map Delegate Methods


- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
	MKOverlayView* overlayView = nil;
	
	if(overlay == _routeLine)
	{
		//if we have not yet created an overlay view for this overlay, create it now. 
		if(nil == _routeLineView)
		{
			_routeLineView = [[[MKPolylineView alloc] initWithPolyline:_routeLine] autorelease];
			_routeLineView.fillColor = [UIColor redColor];
			_routeLineView.strokeColor = [UIColor redColor];
			_routeLineView.lineWidth = 3;
		}
		
		overlayView = _routeLineView;
		
	}
	
	return overlayView;
	
}

//- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark{
//	NSLog(@"Reverse Geocoder completed");
//	mPlacemark=placemark;
//	[londonMapView addAnnotation:placemark];
//}

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
	annView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
	UIImage *pinIconImg =[UIImage imageNamed:@"Location.png"];
	[annView setImage:pinIconImg];
	annView.rightCalloutAccessoryView;
	[annView setRightCalloutAccessoryView:[UIButton buttonWithType:UIButtonTypeInfoDark]];
	//[(MKAnnotationView *)annView setAnimatesDrop:NO];
	[annView setCanShowCallout:YES];
	return annView;
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
	NSLog(@"Anno Tapped");
}

- (void)selectAnnotation:(id <MKAnnotation>)annotation animated:(BOOL)animated {
	
}



#pragma mark - View lifecycle

- (void)viewDidLoad
{
    iSelection =1;
	[self setButtonImagesForSelection];
	//TEST LOAD TWO ANNOTATIONS
    
	GuideMeAppDelegate *appDelegate = (GuideMeAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSDictionary *dicLocation = [appDelegate readPlistIntoDictWithFile:@"Location Details.plist"];
	arryLocationDetails = [[NSMutableArray alloc] initWithArray:[dicLocation objectForKey:@"LatLong"]];
	//[self loadLocationsWithLatLong];
    
    
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
